package cn.com.czpb.client.module.news.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.model.event.PraiseEvent;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommentBean;
import cn.com.czpb.client.model.news.EmptyEntityList;
import cn.com.czpb.client.model.news.IsCollectionEntity;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsDetailBean;
import cn.com.czpb.client.model.news.NewsDetailEntity;
import cn.com.czpb.client.model.news.NewsRelateEntity;
import cn.com.czpb.client.model.news.PraiseNumEntity;
import cn.com.czpb.client.model.usercenter.LevelEntity;
import cn.com.czpb.client.model.video.VideoDetialEntity;
import cn.com.czpb.client.model.video.VideoItemBean;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.module.news.adapter.NewsItemListViewAdapterNew;
import cn.com.czpb.client.module.news.dialog.ReplyDialog;
import cn.com.czpb.client.module.news.view.VideoHeadView;
import cn.com.czpb.client.module.personal.WodeFragment;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.ActionbarUtils;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/8/14.
 */
public class NewsVideoActivity extends MToolBarActivity implements BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.rv_news_id)
    RecyclerView rvNewsId;//recycleview
    @BindView(R.id.comment_number_tx)
    TextView commentNumberTx;//评论数量
    @BindView(R.id.news_detail_ll_bottom1)
    LinearLayout newsDetailLlBottom1;//根布局
    @BindView(R.id.img_back)
    LinearLayout imgBack;
    @BindView(R.id.img_comment)
    ImageView imgComment;
    @BindView(R.id.ll_newdetail_comments)
    LinearLayout llNewdetailComments;
    @BindView(R.id.img_praise)
    ImageView imgPraise;
    @BindView(R.id.praise_number_tx)
    TextView praiseNumberTx;
    @BindView(R.id.ll_newdetail_praise)
    LinearLayout llNewdetailPraise;
    @BindView(R.id.img_collection)
    ImageView imgCollection;
    @BindView(R.id.collection_number_tx)
    TextView collectionNumberTx;
    @BindView(R.id.ll_newdetail_collection)
    LinearLayout llNewdetailCollection;
    @BindView(R.id.img_share)
    ImageView imgShare;
    @BindView(R.id.share_number_tx)
    TextView shareNumberTx;
    @BindView(R.id.ll_newdetail_share)
    LinearLayout llNewdetailShare;
    private NewsItemListViewAdapterNew adapter;
    private VideoItemBean videoItemBean;
    private VideoHeadView headView;
    private String nid;
    private String tid;
    private String rvaue;
    private NewsDetailBean ndb;

    @Override
    public int setLayoutId() {
        return R.layout.activity_video_detail;
    }

    @Override
    public void initView() {
        ActionbarUtils.setMeizuStatusBarDarkIcon(activity, true);
        ActionbarUtils.setMiuiStatusBarDarkMode(activity, true);
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvNewsId.setLayoutManager(manager);
        adapter = new NewsItemListViewAdapterNew(activity,null, false);
        adapter.setOnItemChildClickListener(this);
        rvNewsId.setAdapter(adapter);
        llNewdetailCollection.setVisibility(View.GONE);
        llNewdetailShare.setVisibility(View.GONE);
    }

    @Override
    public void initData() {
        LogUtils.e("--" + spu.getWifiStatus());
        LogUtils.e("--" + spu.getWifi());
        LogUtils.e("--" + spu.getIsNeedNotity());
        Intent intent = getIntent();
        rvaue = intent.getStringExtra("rvalue");
        nid = intent.getStringExtra("nid");
        tid = intent.getStringExtra("tid");
        LogUtils.e("rvalue--" + rvaue + "--nid--" + nid + "--tid--" + tid);
        getDetialVideo();
        getNewsDetails(nid);
    }

    private void getDetialVideo() {
        Map<String, String> map = new HashMap<>();
        map.put("vid", rvaue);
        map.put("device", DeviceUtils.getMyUUID(this));
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        Factory.provideHttpService().getvideoinfo(map)
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<VideoDetialEntity, Boolean>() {
                    @Override
                    public Boolean call(VideoDetialEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<VideoDetialEntity>() {
                    @Override
                    public void call(VideoDetialEntity entity) {
                        if ("200".equals(entity.code)) {
                            videoItemBean = entity.data;
                        } else {
                            TUtils.toast(entity.msg);
                        }
                        setData(videoItemBean);
                        isCollection();

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable----" + throwable + "");
                    }
                });
    }

    private void setData(VideoItemBean itemBean) {
        headView = VideoHeadView.instance(this, itemBean, tid, spu.getIsNeedNotity());
        adapter.addHeaderView(headView.getView());
        getRelateNews();

    }

    private void getNewsDetails(String nid) {
        LogUtils.i("nid-->" + nid);
        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        Factory.provideHttpService()
                .newsDetail(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsDetailEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsDetailEntity entity) {
                        LogUtils.i("detail-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");

                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsDetailEntity>() {
                    @Override
                    public void call(NewsDetailEntity entity) {
                        ndb = entity.data;
                        addVisits(ndb.getTid());
                        commentNumberTx.setText(ndb.getComcount());
                        praiseNumberTx.setText(ndb.getPraisecount());
                        collectionNumberTx.setText(ndb.getFavoritecount());
                        Log.e("entity.data:", entity.data.toString());

                        if ("1".equals(entity.data.getIsfavorite())) {
                            imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                        } else {
                            imgCollection.setImageResource(R.drawable.tabbar_collect);
                        }
                        if ("1".equals(entity.data.getIspraise())) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);
                        } else {
                            imgPraise.setImageResource(R.drawable.tabbar_like);
                        }
                        //添加浏览量
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("detail-->throwable-->" + throwable);
                    }
                });
    }

    //添加浏览量
    public void addVisits(String tid) {
        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        map.put("type", "2");
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("num", "1");
        map.put("tid", tid);

        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }

        map.put("device", DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().addvisit(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntityList) {
                        return true;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntityList) {
                        LogUtils.i("emptyEntityList----" + emptyEntityList.code);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    private void initlevel() {
        String uid = spu.getUser().getUid();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        Factory.provideHttpService().MyLevel(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LevelEntity, Boolean>() {
                    @Override
                    public Boolean call(LevelEntity levelEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LevelEntity>() {
                    @Override
                    public void call(LevelEntity levelEntity) {
                        LogUtils.e("code--" + levelEntity.code);
                        if ("200".equals(levelEntity.code)) {
                            spu.getUser().setUlevel("Lv" + levelEntity.data.getUserinfo().getLevel());
                            Intent intent = new Intent();
                            intent.setAction(WodeFragment.ACTION_USER);
                            activity.sendBroadcast(intent);

                        } else {
                            TUtils.toast(levelEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }

    //是否收藏
    private void isCollection() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() == null) {
            return;
        }
        map.put("typeid", rvaue);
        map.put("uid", spu.getUser().getUid());
        map.put("type", "3");
        Factory.provideHttpService()
                .newsIsCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }

    //评论弹窗
    private void popCommentActivity(final CommentBean commentBean) {
        if (null == videoItemBean) {
            return;
        }
//        if (!"0".equals(videoItemBean.getComflag())) {
//            if (inputPop == null){
//                inputPop = new InputPop(activity, new InputPop.InputListener() {
//                    @Override
//                    public void inputstr(String string) {
//                        if (commentBean != null) {
//                            sendComment(string, commentBean.getCid());
//                        }else {
//                            sendComment(string, null);
//                        }
//                    }
//                });
//            }
//            inputPop.setFocusable(true);
//            inputPop.showAtLocation(findViewById(R.id.root_ll), Gravity.BOTTOM,0,0);
        ReplyDialog dialog = new ReplyDialog(activity, R.style.ChangeNamedialog, new ReplyDialog.InputListener() {
            @Override
            public void inputstr(String string) {
                if (commentBean != null) {
                    sendComment(string, commentBean.getCid());
                } else {
                    sendComment(string, null);
                }
            }
        });
        dialog.show();
//        } else {
//            TUtils.toast("该条新闻不可评论");
//        }
    }

    //发表评论接口
    private void sendComment(String content, String cid) {
        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        map.put("uid", spu.getUser().getUid());
        map.put("type", "VIDEO");
        map.put("content", content);
        map.put("title", videoItemBean.getTitle());
        map.put("json_url", videoItemBean.getTitle());//随便传一个
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity entity) {
                        if ("200".equals(entity.code)) {
                            TUtils.toast("评论成功");
                            commentNumberTx.setText(entity.data.getComcount());
                            initlevel();
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                            setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");
                    }
                });
    }

    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("typeid", nid);
        map.put("uid", spu.getUser().getUid());
        map.put("type", "1");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                TUtils.toast("收藏成功");
                                initlevel();
                                imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                                collectionNumberTx.setText(entity.data.getFavcount());
                            } else {
                                imgCollection.setImageResource(R.drawable.tabbar_collect);
                                collectionNumberTx.setText(entity.data.getFavcount());
                                TUtils.toast("收藏取消");
                            }
                        } else {
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }


    //获取相关新闻列表
    private void getRelateNews() {
        LogUtils.i("init", "getNewslist");
        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        Factory.provideHttpService()
                .newsRelageList(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsRelateEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsRelateEntity entity) {

                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            return true;
                        }
                        LogUtils.i("200--list>失败");
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsRelateEntity>() {
                    @Override
                    public void call(NewsRelateEntity entity) {
                        if ("200".equals(entity.code)) {
                            setListData(entity.data.getList());
                        } else {
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("异常-->" + throwable.toString());
                        adapter.loadMoreFail();
                    }
                });


    }

    public void setListData(List<NewsBean> list) {
        adapter.addHeaderView(getLayoutInflater().inflate(R.layout.view_relate, null));
        adapter.addData(list);
        adapter.notifyDataSetChanged();
        adapter.loadMoreComplete();
        LogUtils.i("size-->" + adapter.getData().size());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        NewsBean newsBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                MyActivitymanager.pushActivity(activity, newsBean, "", "newsitem", newsBean.getRvalue());
                break;
        }
    }

    @Override
    public void finish() {
        if (headView != null) {
            headView.stopVideo();
        }

        super.finish();
    }

    @OnClick({R.id.img_back, R.id.ll_newdetail_comments, R.id.ll_newdetail_praise, R.id.ll_newdetail_collection, R.id.ll_newdetail_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
            case R.id.ll_newdetail_collection:
                if (spu.getUser() != null) {
                    addCollection();
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_share:
                if(spu.getUser()!=null) {
                    String imgurl = null;
                    if (null != ndb.getImgs() && ndb.getImgs().size() > 0) {
                        imgurl = ndb.getImgs().get(0);
                    }
                    String link = ndb.getNewsurl()+ "/uid/" + spu.getUser().getUid();
                    ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, ndb.getTitle(), link, imgurl, 1);
                    dialog.show();
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_comments:
                if (spu.getUser() != null) {
                        PageCtrl.startCommActivity(activity, ndb.getNid(), "3", "VIDEO", ndb.getNid(), ndb);
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }

                LogUtils.e("nid----", ndb.getNid());
                break;
            case R.id.ll_newdetail_praise:
                praiseContent();
                break;
        }
    }

    //赞
    private void praiseContent() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(activity));
        map.put("nid", ndb.getNid());
        map.put("tid", ndb.getTid());
        map.put("type", ndb.getRtype());
        map.put("siteid", "1");
        LogUtils.i("type-->"+ndb.getRtype());
        Factory.provideHttpService().praiseContent(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<PraiseNumEntity>() {
                    @Override
                    public void call(PraiseNumEntity baseEntity) {
                        LogUtils.i("praise-->"+baseEntity.msg);
                        if ("200".equals(baseEntity.code)) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);
                            praiseNumberTx.setText(baseEntity.data.getPraisecount());
                            PraiseEvent praiseEvent = new PraiseEvent();
                            praiseEvent.setNid(ndb.getNid());
                            praiseEvent.setPraisecount(baseEntity.data.getPraisecount());
                            EventBus.getDefault().post(praiseEvent);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("praise-->"+throwable);
                    }
                });

    }

}
